package com.lzx.adx.report.support.strategy.v3.media;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.*;
import com.lzx.adx.report.service.MonitorTemplateService;
import com.lzx.adx.report.support.strategy.v2.media.AbstractCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.VIVO)
public class ViVoChannel extends AbstractChannel {
    @Autowired
    private MonitorTemplateService templateService;

    public static final String baseUrl="https://marketing-api.vivo.com.cn/openapi/v1/advertiser/behavior/upload";

    @Override
    public ResponseEntity callback(ReportDTO reportDTO, OcpxAccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        Map<String, CallTypeMappingDTO> callTypeMap = getCallTypeMap(accountDTO);
        CallTypeMappingDTO callTypeMappingDTO = callTypeMap.get(callType);
        String eventType=callTypeMappingDTO.getMediaReturnType();


        ViVoData viVoData = new ViVoData();
        viVoData.setCvTime(ts);
        viVoData.setCvType(eventType);
        viVoData.setRequestId(reportDTO.getRequestId());
        viVoData.setCreativeId(reportDTO.getContentId());
        if ("PAY".equals(eventType)){
            ViVoData.ExtParam extParam=new ViVoData.ExtParam();
            viVoData.setExtParam(extParam);
        }
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("srcType","WEB");
        paramsMap.put("pageUrl","abc");
        paramsMap.put("srcId",accountDTO.getSrcId());
        paramsMap.put("dataList", Lists.newArrayList(viVoData));
        String resultPams = JSON.toJSONString(paramsMap);
        String url = baseUrl+ "?access_token=" + accountDTO.getMediaKey() + "&timestamp=" + ts + "&nonce=" + IdUtil.fastSimpleUUID() + "&advertiser_id=" + reportDTO.getAid();
        log.info("账号{}，请求id{}给vivo请求地址为地址为：{}，请求参数为{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), url, resultPams);
        String post = HttpUtil.post(url, resultPams);
        log.info("账号{}，请求id{}给vivo请求转换响应的结果为：{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), post);

        accountDTO.setFinalURL(url);
        accountDTO.setBody(post);
        return ResponseEntity.ok(new Result());
    }
}
